<template>
    <div class="container">
        <div class="login-wrapper">
            <div class="header">Sign Up</div>
            <div class="form-wrapper">
                <Form :validation-schema="schema" ref="formCom" v-slot="{ errors }">
                    <Field type="text" name="usernameFn" placeholder="username" class="input-item" v-model="username" />
                    <div class="error" v-if="errors.usernameFn">
                        {{ errors.usernameFn }}
                    </div>
                    <Field type="email" name="emailFn" placeholder="email" class="input-item" v-model="useremail" />
                    <div class="error" v-if="errors.emailFn">
                        {{ errors.emailFn }}
                    </div>
                    <Field type="password" name="passwordFn" placeholder="password" class="input-item" v-model="userpwd" />
                    <div class="error" v-if="errors.passwordFn">
                        {{ errors.passwordFn }}
                    </div>
                </Form>
                <div class="btn" @click="userRegister">Sign Up</div>
                <span><router-link to="login">login in >></router-link></span>
            </div>
        </div>
    </div>
</template>
  
<script setup>
import { ref } from 'vue';
import { useStore } from "vuex"
import { schemavalidate } from "../lib/lib"
import { Form, Field } from 'vee-validate';
import { useRouter } from 'vue-router'

const router = useRouter()
const formCom = ref(null)
const store = useStore()
const username = ref('')
const useremail = ref('')
const userpwd = ref('')

const schema = {
    usernameFn: schemavalidate.usernameFn,
    emailFn: schemavalidate.emailFn,
    passwordFn: schemavalidate.passwordFn
}
const userRegister = async () => {
    const success = await formCom.value.validate()
    if (success.valid) {
        try {
            await store.dispatch("userRegister", {
                username: username.value,
                password: userpwd.value,
                email: useremail.value,
            });
            router.push('/login');
        } catch (error) {
            alert(error.message);
        }
    }
}

</script>
<style lang="less">
@import "../style/login.less";
</style>
  